﻿using UnityEngine;
using System.Collections;

namespace CHFramework
{
    public class ResourcesMgr : Singleton<ResourcesMgr>
    {
        private Hashtable ObjectTable = null;

        public ResourcesMgr()
        {
            ObjectTable = new Hashtable();
        }

        /// <summary>
        /// 加载资源
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="path"></param>
        /// <param name="isCache"></param>
        /// <returns></returns>
        public T LoadAsset<T>(string path, bool isCache) where T : Object
        {
            if (ObjectTable.ContainsKey(path))
                return ObjectTable[path] as T;

            T asset = Resources.Load<T>(path);
            if (isCache)
            {
                if (!ObjectTable.ContainsKey(path))
                    ObjectTable.Add(path, asset);
            }
            return asset;
        }

        /// <summary>
        /// 加载并实例化GameObject
        /// </summary>
        /// <param name="path"></param>
        /// <param name="isCache"></param>
        /// <returns></returns>
        public GameObject LoadAndInstantiateObject(string path, bool isCache)
        {
            GameObject asset = LoadAsset<GameObject>(path, isCache);
            GameObject clone = GameObject.Instantiate<GameObject>(asset);
            clone.name = asset.name;
            return clone;
        }

        /// <summary>
        /// 加载UI预设
        /// </summary>
        /// <param name="path"></param>
        /// <param name="isCache"></param>
        /// <returns></returns>
        public GameObject LoadUIPrefab(string path, bool isCache)
        {
            return LoadAsset<GameObject>(SysDefine.UIPanelPath + path, isCache);
        }
    }
}
